package com.htjc.integral.common.util;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONObject;

import cfca.sadk.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * 生成不带“-”的UUID
 * */
public class CommonUtil {
	private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
	/**
	 * 解密请求密文
	 * 
	 * @param reqStr
	 * @return
	 */
	public static Map<String, Object> decodeReqStr(String reqStr) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("isSuccess", true);
		try {
			byte srcReqByte[] = Base64.decode(reqStr);
			String srcReqStr = "";
			srcReqStr = new String(srcReqByte, "utf-8");
			log.info("解密后的明文为：" + srcReqStr);
			retMap.put("srcReqStr", srcReqStr);
		} catch (UnsupportedEncodingException e) {
			retMap.put("isSuccess", false);
			log.error("解密请求密文异常", e);
		}
		return retMap;
	}
	
	// 判断是否是JSON格式
	public static boolean isJsonStr(String jsonStr) {
		boolean flag = false;
		try {
			net.sf.json.JSONObject.fromObject(jsonStr);
			flag = true;
		} catch (Exception e) {
			log.error("");
		}
		return flag;
	}

	// 参数名校验
	public static boolean checkKeyName(String[] rightParam, JSONObject jo) {
		boolean flag = false;
		try {
			int le = jo.size();
			String[] newStr = new String[le];
			String[] newJo = new String[le];
			System.arraycopy(rightParam, 0, newStr, 0, le);
			System.arraycopy(jo.keySet().toArray(), 0, newJo, 0, le);
			Arrays.sort(newStr);
			Arrays.sort(newJo);
			if (Arrays.equals(newStr, newJo)) {
				flag = true;
			}
		} catch (Exception e) {
			log.error("参数名校验异常", e);
		}
		return flag;
	}
	
	/**
	 * 必要字段验证
	 * 
	 * @param rightParam
	 * @param dataBody
	 * @return
	 */
	public static boolean checkNecessaryKey(String[] rightParam, JSONObject jo) {
		@SuppressWarnings("unchecked")
		Set<String> keySet = jo.keySet();
		boolean flag = false;
		for (int i = 0; i < rightParam.length; i++) {
			flag = false;
			Iterator<String> it = keySet.iterator();
			while (it.hasNext()) {
				String key = it.next();
				if (key.equals(rightParam[i])) {
					flag = true;
					break;
				}
			}
			if (!flag) {
				break;
			}
		}
		return flag;
	}

	// 手机号格式校验
	public static boolean checkMobile(String mobile) {
		String regex = "^1(3|4|5|7|8)[0-9]{9}$";
		Pattern pa = Pattern.compile(regex);
		Matcher mat = pa.matcher(mobile);
		boolean b = mat.matches();
		return b;
	}
	
	public static boolean isNull(String str) {
		if (str == null || "".equals(str)) {
			return true;
		}
		return false;
	}

}
